/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.hualu.zks.GUI;
//import demoframe1.DocJFrame;


import com.hualu.zks.httpclient.AsyncHTTPCallback;
import com.hualu.zks.httpclient.GetFileList;
import com.hualu.zks.httpclient.Delete_Rename;
import com.hualu.lgproject.CommonUtils.ControlConstants;
import com.hualu.lgproject.CommonUtils.ErrCode;
import com.hualu.zks.CommonUtils.Globalparameters;
import com.hualu.zks.CommonUtils.InfoDialog;
import com.hualu.zks.CommonUtils.LGDialog;
import com.hualu.lgproject.CommonUtils.ProtocolUtils;
import com.hualu.lgproject.Model.File;
import com.hualu.zks.Model.Node;
import com.hualu.zks.GUI.JFrame_File;
import static com.hualu.zks.GUI.JFrame_File.fileDao;
import static com.hualu.zks.GUI.JFrame_File.fileList;
import static com.hualu.zks.GUI.JFrame_File.nodeDao;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;


/**
 *
 * @author Administrator
 */
public class JFrame_FileEdit extends javax.swing.JFrame {
    public static File file;
    public static JFrame_File docjframe;
    private static String ipString;
    private static int number;
    /**
     * Creates new form Change2JFrame
     */
    public JFrame_FileEdit(String ipString,int number,File file,JFrame_File docjframe) {
        initComponents();
        this.ipString=ipString;
        JFrame_FileEdit.file=file;
        this.number=number;
        JFrame_FileEdit.docjframe=docjframe;
        setText(file);
    }


    private void  setText(File file) {
    	jTextField1.setText(file.getName());
    	jTextField2.setText(file.getName());
	}
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jButton_Enter = new javax.swing.JButton();
        jButton_Cancel = new javax.swing.JButton();
        jLabel_biaoti4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("文件名称修改");
        setIconImage(Toolkit.getDefaultToolkit().getImage("pic\\bfhl.jpg"));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("旧文件名");

        jLabel2.setText("新文件名");

        jTextField1.setEditable(false);
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton_Enter.setText("确定");
        jButton_Enter.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton_EnterMouseClicked(evt);
            }
        });
        jButton_Enter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_EnterActionPerformed(evt);
            }
        });

        jButton_Cancel.setText("取消");
        jButton_Cancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton_CancelMouseClicked(evt);
            }
        });
        jButton_Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CancelActionPerformed(evt);
            }
        });

        jLabel_biaoti4.setFont(new java.awt.Font("华文行楷", 0, 24)); // NOI18N
        jLabel_biaoti4.setText("修改文件名称");

        jLabel3.setText("注意：文件名只能使用英文，数字，下划线");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel_biaoti4)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(81, 81, 81)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
                                    .addComponent(jTextField2)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton_Enter, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(62, 62, 62)
                                .addComponent(jButton_Cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(43, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel_biaoti4)
                .addGap(46, 46, 46)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Enter)
                    .addComponent(jButton_Cancel))
                .addGap(54, 54, 54))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton_EnterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_EnterMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton_EnterMouseClicked

    private void jButton_EnterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EnterActionPerformed
        // TODO add your handling code here:
        if(jTextField2.getText().equals(jTextField1.getText()))
            {
               JOptionPane.showMessageDialog(null, Globalparameters.strNoChange,Globalparameters.strInformation, JOptionPane.INFORMATION_MESSAGE);                
               return;
            }
        if (jTextField2.getText().trim().matches("[A-Za-z0-9_]+")) {
        try {
            Delete_Rename rename = new Delete_Rename();
            GetFileList getdata = new GetFileList();
            //尝试获取一次 检测刻录机是否在休眠
            int sec = 3;
            while(1==getdata.checkSleep(docjframe.getURL())){
                try {
                    Thread.sleep(3*1000);
//                    System.out.println("等待"+sec+"秒...");
                    sec=sec+3;
                } catch (InterruptedException ex) {
                    Logger.getLogger(JFrame_File.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            rename.Rename(new AsyncHTTPCallback() {
                @Override
                public int onComplete(HttpResponse httpResponse) {
                    //获取响应信息
                    HttpEntity entity = httpResponse.getEntity();
                    if (entity.getContentLength() != 0) {
                        try {
                            System.err.println("重命名失败!");
                            InputStreamReader rr = null;
                            try {
                                rr = new InputStreamReader(entity.getContent(), "UTF-8");
                            } catch (IOException | IllegalStateException ex) {
                                Logger.getLogger(JFrame_FileEdit.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            BufferedReader reader = new BufferedReader(rr);
                            StringBuilder builder = new StringBuilder();
                            for (String line = reader.readLine(); line != null; line = reader
                                    .readLine()) {
                                builder.append(line);
                            }
                            String[] builderSplit = builder.toString().split(",");
                            System.err.println("错误码："+builderSplit[0]);
                            JOptionPane.showMessageDialog(null, ErrCode.getErrMessage(builderSplit[0]), "警告", JOptionPane.WARNING_MESSAGE);
                            rr.close();
                            return -1;
                            //在这里获取返回信息，判断成功失败，并进行相应操作。更改数据库应该在判定结果为成功后进行
                        } catch (IOException ex) {
                            Logger.getLogger(JFrame_FileEdit.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        File fileNew = new File();
                        fileNew = file;
                        System.out.println("重命名成功!");
                        fileNew.setName(jTextField2.getText());
                        docjframe.fileList.set(number, fileNew);
                        JFrame_FileEdit.this.dispose();
                        docjframe.Refresh();
                        docjframe.setVisible(true);
                        System.out.println("名字更改执行语句完成");
                        InfoDialog d = new InfoDialog();  
                        d.showDialog(new JFrame(), "修改文件名成功！", 5);// TimerTest是程序主窗口类，弹出的对话框10秒后消失
                        return 0;
                    }
                    return -2;
                }
            }, docjframe.getURL(), file, jTextField2.getText());

//              final Socket cs  =  ProtocolUtils.createConnection(ipString, ControlConstants.port);                          
//              ProtocolUtils.sendPostProtocol(cs, ControlConstants.RENAME_FILE,parArrayList,
//                      new Thread(new Runnable() {
//
//                  @Override
//                  public void run() {
//                      if (ProtocolUtils.getMessage(cs).equals(ControlConstants.success)) {
//                            File fileNew = new File();
//                            fileNew.setFileId(file.getFileId());
//                            fileNew.setIsDownLoaded(file.getIsDownLoaded());
//                            fileNew.setName(jTextField2.getText());
//                            docjframe.fileList.set(number, fileNew);
//                            JFrame_FileEdit.this.dispose();
//                            docjframe.Refresh();
//                            docjframe.setVisible(true);
//                      }else{
//                           JOptionPane.showMessageDialog(null, Globalparameters.strFail,Globalparameters.strNote,JOptionPane.INFORMATION_MESSAGE);                
//                      }
//                  }
//              }));
          } catch (IOException ex) {
              Logger.getLogger(JFrame_File.class.getName()).log(Level.SEVERE, null, ex);
          }
        }else{
            JOptionPane.showMessageDialog(null, "文件名只能由数字字母和下划线组成!", "警告", JOptionPane.WARNING_MESSAGE);
            jTextField2.requestFocus();
        }
    }//GEN-LAST:event_jButton_EnterActionPerformed

    private void jButton_CancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_CancelMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton_CancelMouseClicked

    private void jButton_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelActionPerformed
        // TODO add your handling code here:
        this.dispose();
        docjframe.setVisible(true);
    }//GEN-LAST:event_jButton_CancelActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrame_FileEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrame_FileEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrame_FileEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrame_FileEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrame_FileEdit(ipString,number,file,docjframe).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_Cancel;
    private javax.swing.JButton jButton_Enter;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel_biaoti4;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
